package com.common.helper;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.commons.lang3.reflect.MethodUtils;

/*
 * 枚举类型帮助类
 */
public class EnumHelper {

	//通过Key获取Label 
	public static String getLableByKey(Class<?> ref, Object code) {
		return GetEnumMap(ref).get(code);
	}
	
	//通过Label获取Key
	public static Integer getKeyByLabel(Class<?> ref, String label) {
		Integer key = Integer.MIN_VALUE;
		Map<Integer, String> enumMaps = GetEnumMap(ref);

		for (Map.Entry<Integer, String> map : enumMaps.entrySet()) {
			if (map.getValue().equals(label)) {
				key = map.getKey();
				break;
			}
		}
		return key;
	}
	
	//以Label 为Key ，Key为Value的键值对
	public static <T> Map<String, String> GetEnumLabKeyMap(Class<T> ref) {		
		Map<String, String> currentMap = new LinkedHashMap<String, String>();
		for (Map.Entry<Integer, String> item : GetEnumMap(ref).entrySet()) {
			currentMap.put(item.getValue(), item.getKey().toString());
		}
		return currentMap;
	}

	public synchronized static <T> Map<Integer, String> GetEnumMap(Class<T> ref) {
		Map<Integer, String> map = new LinkedHashMap<Integer, String>();
		if (ref.isEnum()) {
			T[] ts = ref.getEnumConstants();
			for (T t : ts) {
				Enum<?> currentEnum = (Enum<?>) t;

				String lable = getInvokeValue(t, "getLabel");// 自定义方法获取描述
				if (lable == null || lable.isEmpty()) {
					String text = getInvokeValue(t, "getText");//默认获取枚举名称
					lable = text == null ? currentEnum.name() : text;
				}

				String code = getInvokeValue(t, "getKey");// 获取Code值
				if (code == null || code.isEmpty()) {
					code = currentEnum.ordinal()+"";
				}
				map.put(Integer.parseInt(code), lable);
			}
		}
		return map;
	}

	private static <T> String getInvokeValue(T t, String methodName) {
		Method method = MethodUtils.getAccessibleMethod(t.getClass(),
				methodName);
		if (null == method) {
			return null;
		}
		try {
			return method.invoke(t) + "";
		} catch (Exception e) {
			return null;
		}
	}
}
